package com.cn.config;

import com.cn.io.Resources;
import com.cn.pojo.Configuration;
import com.cn.pojo.MapperdStatement;
import com.cn.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 封装mapper
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    // 数据库操作标签
    private List<String> curds = new ArrayList<>();

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;

        curds.add("select");
        curds.add("update");
        curds.add("delete");
        curds.add("insert");
    }

    public void parse(String path) throws DocumentException {
        // 读取mapper.xml中配置的mapper路径
        InputStream resourceAsStream = Resources.getResourceAsStream(path);
        Document document = new SAXReader().read(resourceAsStream);

        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        // 封装mapperdStatement ，并放入configuration中
        for (String s: curds) {
            List<Element> list = rootElement.selectNodes("//" + s);
            if(list != null && list.size() > 0){

                for(Element e : list){
                    String id = e.attributeValue("id");
                    String resultType = e.attributeValue("resultType");
                    String paramterType = e.attributeValue("paramterType");
                    String sql = e.getTextTrim();

                    MapperdStatement mapperdStatement = new MapperdStatement();
                    mapperdStatement.setId(id);
                    mapperdStatement.setParamterType(paramterType);
                    mapperdStatement.setResultType(resultType);
                    mapperdStatement.setSql(sql);
                    // 注入 执行类型
                    mapperdStatement.setSqlCommandType(SqlCommandType.valueOf(s.toUpperCase()));

                    this.configuration.getStatementMap().put(namespace + "." + id, mapperdStatement);
                }
            }
        }
        System.out.println(configuration);
    }


    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }
}
